package com.test;

import java.io.*;
import java.util.*;
import java.util.zip.*;

//工作线程
public class GZipRunnable implements Runnable {
	private List pool;
	private static int filesCompressed = 0;

	public GZipRunnable(List pool) {
		this.pool = pool;
	}

	// 同步方法用于修改已完成压缩的文件数目
	private static synchronized void incrementFilesCompressed() {
		filesCompressed++;
	}

	public void run() {
		// 工作线程的工作条件
		while (filesCompressed != GZipAllFiles.getNumberOfFilesToBeCompressed()) {
			File input = null;
			// 同步存放待压缩文件对象的任务池
			synchronized (pool) {
				while (pool.isEmpty()) {
					if (filesCompressed == GZipAllFiles.getNumberOfFilesToBeCompressed()) {
						System.out.println("Thread ending");
						return;
					}
					try {
						// 等待任务
						pool.wait();
					} catch (InterruptedException ex) {
						ex.printStackTrace();
					}
				}
				// 取出任务
				input = (File) pool.remove(pool.size() - 1);
				incrementFilesCompressed();
			}
			// don't compress an already compressed file
			if (!input.getName().endsWith(".gz")) {
				try {
					InputStream in = new FileInputStream(input);
					in = new BufferedInputStream(in);
					File output = new File(input.getParent(), input.getName() + ".gz");
					if (!output.exists()) { // Don't overwrite an existing file
						OutputStream out = new FileOutputStream(output);
						out = new GZIPOutputStream(out);
						out = new BufferedOutputStream(out);
						int b;
						while ((b = in.read()) != -1)
							out.write(b);
						out.flush();
						out.close();
						in.close();
					}
				} catch (IOException ex) {
					System.err.println(ex);
				}
			} // end if
		} // end while
	} // end run
} // end ZipThread
